package com.losdun.aftersales.jobs;

import com.losdun.aftersales.domain.ContractOrder;
import com.losdun.aftersales.enums.OrderStatusEnum;
import com.losdun.aftersales.liteweb.LitewebClient;
import com.losdun.aftersales.liteweb.vo.TaskVo;
import com.losdun.aftersales.liteweb.vo.req.TaskQueryReq;
import com.losdun.aftersales.manager.NoticeManager;
import com.losdun.aftersales.service.IContractOrderService;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/9/29
 **/
@Slf4j
@Component("litewebTask")
public class LitewebTask {

    @Autowired
    private LitewebClient litewebClient;

    @Autowired
    private IContractOrderService contractOrderService;

    @Autowired
    private NoticeManager noticeManager;
    public void queryTaskList(){
        log.info("开始执行Liteweb查询任务");
        List<ContractOrder> contractOrders = queryUnShippingOrder();
        if(Collections.isEmpty(contractOrders)){
            log.info("没有查询的订单==任务over");
            return;
        }
        contractOrders.forEach(t->{
            log.info("开始处理订单:{}", t.getOrderNo());
            try {
                List<TaskVo> stepList = queryRemoteStep(t.getOrderNo());
                if(Collections.isEmpty(stepList)){
                    return;
                }
                if(t.getStatus().equals(OrderStatusEnum.AUDIT_PASS.getValue()) || t.getStatus().equals(OrderStatusEnum.WAIT_AUDIT.getValue())){
                    //设计已确认，判断有任务就设置成工厂制作中
                    TaskVo firstTaskVo = stepList.get(0);
                    contractOrderService.updateStatus(t.getId(), OrderStatusEnum.PRODUCTING.getValue(), LocalDate.parse(firstTaskVo.getProcessStartRealTime()));
                }else if(t.getStatus().equals(OrderStatusEnum.PRODUCTING.getValue())){
                    //工厂制作中，判断任务是否都完成，都完成就改成发货中
                    TaskVo lastTaskVo = stepList.get(stepList.size()-1);
                    if(lastTaskVo.getProcessStatus().equals(20)){
                        contractOrderService.updateStatus(t.getId(), OrderStatusEnum.SHIPPING.getValue(), LocalDate.parse(lastTaskVo.getProcessEndRealTime()));
                        //发送订单通知
                        noticeManager.orderSendNotice(t);
                    }
                }
            } catch (Exception e) {
               log.error("处理订单:{}异常", t.getOrderNo(), e);
            }
        });
    }
    private List<ContractOrder> queryUnShippingOrder(){
        return contractOrderService.queryUnShippingOrder();
    }

    private List<TaskVo> queryRemoteStep(String orderNo) {
        TaskQueryReq req=new TaskQueryReq();
        req.setProjectCode(orderNo);
        return litewebClient.queryTaskList(req);
    }
}
